package com.wjj.demo.view;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.wjj.demo.R;


/**
 * 上拉加载的SwipeRefreshLayout
 * Created by Wjj on 16/10/28.
 */
public class PullUpSwipeRefreshLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {
    /**
     * 滑动到最下面时的上拉操作
     */

    private int mTouchSlop;
    /**
     * listView实例
     */
    private ListView mListView;

    /**
     * 上拉监听器, 到了最底部的上拉加载操作
     */
    private OnLoadListener mOnLoadListener;

    /**
     * ListView的加载中footer
     */
    private View mListViewFooter;

    /**
     * 按下时的y坐标
     */
    private int mYDown;
    /**
     * 抬起时的y坐标, 与mYDown一起用于滑动到底部时判断是上拉还是下拉
     */
    private int mLastY;
    /**
     * 是否在加载中 ( 上拉加载更多 )
     */
    private boolean isLoading = false;

    ProgressBar mProgressBar;

    /**
     * @param context
     */
    public PullUpSwipeRefreshLayout(Context context) {
        this(context, null);
        init(context);
    }

    public PullUpSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
//        setColorSchemeResources(R.color.pullToRefresh_yellow, R.color.pullToRefresh_gray,
//                R.color.pullToRefresh_yellow, R.color.pullToRefresh_gray);
    }


    /**
     * 设置上拉加载等待动画
     *
     * @param context
     * @param mListView
     */
    public void setFooterView(Context context, ListView mListView) {
        this.mListView = mListView;
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

        mListViewFooter = LayoutInflater.from(context).inflate(R.layout.pull_up_refresh, null, false);
//        mProgressBar = (ProgressBar) mListViewFooter.findViewById(R.id.pull_to_refresh_load_progress);
//        Rect bounds = mProgressBar.getIndeterminateDrawable().getBounds();
//        mProgressBar.setIndeterminateDrawable(new ChromeFloatingCirclesDrawable.Builder(context)
//                .colors(getResources().getIntArray(R.array.google_colors))//google的等待动画
//                .build());
//        mProgressBar.getIndeterminateDrawable().setBounds(bounds);
        mListViewFooter.setVisibility(View.GONE);//先不显示
        mListView.addFooterView(mListViewFooter, null, false);
        mListView.setFooterDividersEnabled(false);//不要footer之间的分隔线，貌似没啥用
        mListView.setOnScrollListener(this);
    }

    //    @Override
    //    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    //        super.onLayout(changed, left, top, right, bottom);
    //
    //        // 初始化ListView对象
    //        if (mListView == null) {
    //            getListView();
    //        }
    //    }

    /**
     * 获取childView对象
     */
    private void getListView() {
        int childs = getChildCount();
        if (childs > 0) {
            View childView = getChildAt(0);
            if (childView instanceof ListView) {
                mListView = (ListView) childView;
                // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
                //mListView.setOnScrollListener(this);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                // 按下
                mYDown = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                // 移动
                mLastY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                // 抬起
                if (canLoad()) {
                    loadData();
                }
                break;
            default:
                break;
        }
        try {
            return super.dispatchTouchEvent(event);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            return true;
        }
    }

    /**
     * 是否可以加载更多, 条件是到了最底部, listView不在加载中, 且为上拉操作.
     *
     * @return
     */
    private boolean canLoad() {
        return isBottom() && !isLoading && isPullUp();
    }


    /**
     * 判断是否到了最底部
     */
    private boolean isBottom() {
        if (mListView != null && mListView.getAdapter() != null) {
            return mListView.getLastVisiblePosition() == (mListView.getAdapter().getCount() - 1);
        }
        return false;
    }

    /**
     * 是否是上拉操作
     *
     * @return
     */
    private boolean isPullUp() {
        return (mYDown - mLastY) >= mTouchSlop;
    }

    /**
     * 如果到了最底部,而且是上拉操作.那么执行onLoad方法
     */
    private void loadData() {
        if (mOnLoadListener != null) {
            // 设置状态
            setLoading(true);
            //
            mOnLoadListener.onLoad();
        }
    }

    /**
     * @param loading
     */
    public void setLoading(boolean loading) {
        isLoading = loading;
        if (isLoading) {
            //            if (isRefreshing()) {
            //                setRefreshing(false);
            //            }
            if (mListView.getFooterViewsCount() == 0) {
                mListView.addFooterView(mListViewFooter);
                mListView.setSelection(mListView.getAdapter().getCount() - 1);
            } else {
                mListViewFooter.setVisibility(VISIBLE);
            }
        } else {
            if (mListView.getAdapter() instanceof HeaderViewListAdapter) {
                mListView.removeFooterView(mListViewFooter);
            } else {
                mListViewFooter.setVisibility(View.GONE);
            }
            mYDown = 0;
            mLastY = 0;
        }

    }

    /**
     * @param loadListener
     */
    public void setOnLoadListener(OnLoadListener loadListener) {
        mOnLoadListener = loadListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {
        // 滚动时到了最底部也可以加载更多
        if (canLoad()) {
            loadData();
        }
    }

    /**
     * 加载更多的监听器
     *
     * @author mrsimple
     */
    public interface OnLoadListener {
        void onLoad();
    }
}
